import React, { useEffect, useState } from 'react';
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from 'react-sortable-hoc';
import { Tabs } from 'antd';

const { TabPane } = Tabs;

const DragHandle = SortableHandle(({ name }) => {
  return <div style={{ cursor: 'grab', flex: 1 }}>{name}</div>;
});

const Item = ({ children }) => {
  return (
    <li style={{ width: 200, height: 200, background: 'red', margin: 5 }}>
      <DragHandle name={'title'} />
      {children}
    </li>
  );
};

const SortableItem = SortableElement(({ children }) => {
  useEffect(() => {
    console.log(123);
  }, []);
  return <Item>{children}</Item>;
});

const SortableList = SortableContainer(({ items, activeKey }) => {
  useEffect(() => {
    console.log(activeKey);
  }, [activeKey]);
  return (
    <ul
      style={{
        display: 'flex',
        flexWrap: 'wrap',
        listStyle: 'none',
        width: 500,
      }}
    >
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index}>
          {value}
        </SortableItem>
      ))}
    </ul>
  );
});

const SortableHoc = () => {
  const [activeKey, setActiveKey] = useState('1');
  const onSortEnd = (...a) => {
    console.log(a);
  };

  return (
    <>
      {/*
      destroyInactiveTabPane 这个属性设置上了之后,切换后,子组件还是会触发 useEffect 挂载后
      写这个组件的目的:
        为了测试, Tabs 切换后不销毁子组件,看看子组件的 更新后 生命周期是怎么触发的
      结论:
        哪怕被隐藏的子组件的更新后也会触发
    */}
      <Tabs activeKey={activeKey} onChange={setActiveKey}>
        <TabPane key="1" tab="F1">
          {activeKey === '1' && (
            <SortableList
              items={[
                'Item 1',
                'Item 2',
                'Item 3',
                'Item 4',
                'Item 5',
                'Item 6',
              ]}
              onSortEnd={onSortEnd}
              axis="xy"
              useDragHandle
              activeKey={activeKey}
            />
          )}
        </TabPane>
        <TabPane key="2" tab="F2">
          {activeKey === '2' && (
            <SortableList
              items={[
                'Item 1',
                'Item 2',
                'Item 3',
                'Item 4',
                'Item 5',
                'Item 6',
              ]}
              onSortEnd={onSortEnd}
              axis="xy"
              useDragHandle
              activeKey={activeKey}
            />
          )}
        </TabPane>
      </Tabs>
      ;
    </>
  );
};

export default SortableHoc;
